<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我的优惠卷',
  },
}
</route>
<template>
  <view class="coupon-page">
    <wd-sticky>
      <wd-search
        style="box-sizing: border-box; width: 750rpx"
        v-model="searchKey"
        hide-cancel
        placeholder="搜索优惠券名称"
        @search="handleSearch"
        @clear="handleSearch"
      />
    </wd-sticky>

    <scroll-view
      class="coupon-list"
      scroll-y
      refresher-enabled
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore"
    >
      <coupon-card
        v-for="coupon in couponList"
        :key="coupon.id"
        :coupon="coupon"
        :disabled="coupon.status === 2"
      />

      <wd-divider v-if="isEmpty">暂无优惠券</wd-divider>
      <wd-divider v-else-if="isLoading">加载中...</wd-divider>
      <wd-divider v-else>没有更多了</wd-divider>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getList } from '@/service/goods/coupon/coupon'
import type { CouponInfoVo } from '@/service/goods/coupon/coupon.d'
import CouponCard from './components/coupon-card.vue'

const searchKey = ref('')
const isLoading = ref(false)
const isLocked = ref(false) // 加载锁
const currentPage = ref(1)
const pageSize = 10
const couponList = ref<CouponInfoVo[]>([])
const hasMore = ref(true)

// 初始化加载
onLoad(async () => {
  await loadData(true)
})

const loadData = async (reset = false) => {
  if (isLocked.value || !hasMore.value) return
  isLocked.value = true
  isLoading.value = true

  try {
    const params = {
      current: currentPage.value,
      size: pageSize,
      keyWord: searchKey.value,
    }

    const { data } = await getList(params as any)
    hasMore.value = data.current * data.size < data.total

    if (reset) {
      couponList.value = data.records
      currentPage.value = 1
    } else {
      couponList.value = [...couponList.value, ...data.records]
    }

    if (data.records.length) currentPage.value++
  } finally {
    isLoading.value = false
    isLocked.value = false
    uni.stopPullDownRefresh()
  }
}

const handleSearch = () => {
  hasMore.value = true
  currentPage.value = 1

  loadData(true)
}

const onRefresh = () => loadData(true)

const loadMore = () => {
  if (hasMore.value && !isLoading.value) {
    loadData()
  }
}

const isEmpty = computed(() => couponList.value.length === 0)
</script>

<style lang="scss" scoped>
.coupon-page {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .coupon-list {
    box-sizing: border-box;
    flex: 1;
    padding: 20rpx;
  }
}
</style>
